//
//  LoopComposePicViewController.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/17.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit

let colCount:CGFloat = 3
let picSelectorMargin:CGFloat = 4
let picSelectorWidth = (screenWidth - (colCount + 1) * picSelectorMargin) / colCount
let maxPicCount = 9

private let composePicId = "composePicCell"

class LoopComposePicViewController: UICollectionViewController {

    
    lazy var picSelectedArray = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.collectionView!.register(LoopComposePicCell.self, forCellWithReuseIdentifier: composePicId)

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let delta = picSelectedArray.count == maxPicCount ? 0 : 1
        return picSelectedArray.count + delta
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: composePicId, for: indexPath) as! LoopComposePicCell
        cell.delegate = self
        cell.backgroundColor = #colorLiteral(red: 0.9431162778, green: 0.9333191193, blue: 0.9431710025, alpha: 1)
        self.view.isHidden = picSelectedArray.count == 0
        if indexPath.item == picSelectedArray.count{
            cell.image = nil
        }else{
            cell.image = picSelectedArray[indexPath.item]
        
        }
        
        return cell
    }

}

extension LoopComposePicViewController: LoopComposePicCellDelegate{

    func userWillChoosePic(cell:LoopComposePicCell?){
    
        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        self.present(picker, animated: true, completion: nil)
        
//        self.view.isHidden = false
    }
    
    func userWillRemovePic(cell:LoopComposePicCell){
    
        guard let index = collectionView?.indexPath(for: cell) else{
        
            return
        }
        
        picSelectedArray.remove(at: index.item)
        
        self.collectionView?.reloadData()
        
//        self.view.isHidden = picSelectedArray.count == 0
    }

}


extension LoopComposePicViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
        print(info)
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        self.picSelectedArray.append(image.scaleImage(width: screenWidth))
        
        dismiss(animated: true, completion: nil)
        
        self.collectionView?.reloadData()
    
    }

}
